package com.fastjpa;

import com.efeichong.util.EntityUtils;
import lombok.Data;
import org.springframework.validation.BindingResult;
import java.io.Serializable;

import static com.fastjpa.Constance.*;


/**
 * 返回值统一封装
 *
 * @author
 * @create 2019-02-16 16:34
 **/
@Data
public class ResponseData<T> implements Serializable {

    private static final long serialVersionUID = 4338293435526973422L;

    private int status = SUCCESS_CODE;

    private String message = SUCCESS_MESSAGE;

    private T data;

    public ResponseData() {

    }

    public ResponseData(T data) {
        this.data = data;
    }

    public ResponseData(int status, String message) {
        this.status = status;
        this.message = message;
    }

    public ResponseData(int status, String message, T data) {
        this.status = status;
        this.message = message;
        this.data = data;
    }

    public ResponseData<T> setMessage(String message) {
        this.message = message;
        return this;
    }

    public ResponseData<T> setData(T data) {
        this.data = data;
        return this;
    }

    public static ResponseData success() {
        return new ResponseData();
    }

    public static ResponseData success(Object data) {
        return new ResponseData(data);
    }

    public static ResponseData failure() {
        return new ResponseData(FAILED_CODE, "failed");
    }

    public static ResponseData failure(String message) {
        return new ResponseData(FAILED_CODE, message);
    }

    public static ResponseData loginExpire() {
        return new ResponseData(LOGIN_EXPIRED_CODE, LOGIN_EXPIRED_MESSAGE);
    }

    public static ResponseData validResult(BindingResult result) {
        String defaultMessage = result.getAllErrors().get(0).getDefaultMessage();
        if (EntityUtils.isEmpty(defaultMessage)) {
            return new ResponseData();
        } else {
            return new ResponseData(FAILED_CODE, defaultMessage);
        }
    }
}

